package com.hyjy.music.util

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

/**
 * RecyclerView通用适配器
 */
abstract class RecyclerViewCommonAdapter<T> constructor(
    private var context: Context,
    private var dataList: List<T>,
    @LayoutRes private var itemLayoutRes: Int,
    private var listener: OnItemListener? = null
) : RecyclerView.Adapter<RecyclerViewCommonAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(context).inflate(itemLayoutRes, parent, false)
        val viewHolder = ViewHolder(itemView)
        getItemViewId().forEach {
            viewHolder.viewCache[it] = itemView.findViewById(it)
        }
        itemView.setOnClickListener {
            listener?.onItemClick(it, viewHolder.adapterPosition)
        }
        itemView.setOnLongClickListener {
            listener?.onItemLongClick(it, viewHolder.adapterPosition)
            true
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        setItemData(holder, position, dataList[position])
    }

    override fun getItemCount(): Int = dataList.size

    /**
     * 返回Item中所有View的id
     */
    abstract fun getItemViewId(): IntArray

    /**
     * 设置Item数据
     */
    abstract fun setItemData(holder: ViewHolder, position: Int, item: T)

    /**
     * 刷新数据
     *
     * @param list 新的数据源
     */
    fun refreshData(list: List<T>) {
        this.dataList = list
        notifyDataSetChanged()
    }

    /**
     * 通用ViewHolder
     */
    class ViewHolder constructor(val view: View) : RecyclerView.ViewHolder(view) {
        var viewCache: SparseArray<View> = SparseArray()

        /**
         * 通过控件的Id获取对应的控件
         */
        inline fun <reified T : View> getItemChildView(@IdRes viewId: Int): T? {
            val view = viewCache[viewId]
            return if (view is T) {
                view
            } else {
                null
            }
        }

        /**
         * 给TextView赋值
         */
        fun setTextView(@IdRes id: Int, text: String?): ViewHolder {
            getItemChildView<TextView>(id)?.text = text
            return this
        }

        /**
         * 给ImageView赋值
         */
        fun setImageView(@IdRes id: Int, @DrawableRes drawableId: Int): ViewHolder {
            getItemChildView<ImageView>(id)?.setImageResource(drawableId)
            return this
        }
    }

    /**
     * 点击和长按监听,按需重写.
     */
    interface OnItemListener {
        fun onItemClick(view: View, position: Int) {}
        fun onItemLongClick(view: View, position: Int) {}
    }
}